namespace SimpleWebServices.Web.Routing
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Configuration;

    public sealed class FileRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData result = null;

            Route route = FileRoute.GetRoute(httpContext);
            if (null != route)
            {
                result = route.GetRouteData(httpContext);
            }

            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            if (null == requestContext)
            {
                throw new ArgumentNullException("requestContext");
            }

            VirtualPathData result = null;

            Route route = FileRoute.GetRoute(requestContext.HttpContext);
            if (null != route)
            {
                result = route.GetVirtualPath(requestContext, values);
            }

            return result;
        }

        private static Route GetRoute(HttpContextBase httpContext)
        {
            if (null == httpContext)
            {
                throw new ArgumentNullException("httpContext");
            }

            Route result = null;

            string path = httpContext.Request.Path;
            if (FileConfiguration.Settings().Contains(path))
            {
                result = new Route(path.Substring(1), new MvcRouteHandler())
                {
                    Defaults = new RouteValueDictionary(new { controller = "File", action = "Representation" }),
                    Constraints = new RouteValueDictionary()
                };
            }

            return result;
        }
    }
}